<template>
  <!-- eslint-disable vue/no-use-v-if-with-v-for,vue/no-confusing-v-for-v-if -->
  <div class="iot-energy app-container">
    <lb-layout
      v-loading="$store.getters.loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="#a19f9fb0;"
    >
      <div>
        <el-row class="tab-area">
          <el-col :span="24">
            <el-tabs
              v-model="activeName"
              @tab-click="handleChangetab"
              class="text-tabs TTB-gutter"
            >
              <el-tab-pane
                v-for="(item, index) in tabArr"
                :key="index"
                :label="item.label"
                :name="item.value"
                v-hasPermi="item.hasPermi"
              ></el-tab-pane>
              <!-- v-if="item.show" -->
            </el-tabs>
          </el-col>
        </el-row>
        <el-row v-loading="tabloading">
          <el-col :span="24">
            <aps-form
              :config="apsForm.formConfig"
              :model="apsForm.formData"
              :formRef="apsForm.formRef"
              :labelWidth="apsForm.labelWidth"
              ref="form"
            ></aps-form>
            <el-row>
              <el-col :span="24" class="chart-area">
                <div
                  v-if="
                    (activeName === '0' && radio === 0) || activeName === '1'
                  "
                  class="total"
                >
                  <span>{{ sumName }}</span> <span>{{ sumValue }}</span>
                </div>
                <div v-show="activeName === '0'" class="sum-area">
                  <el-radio-group
                    v-model="radio"
                    @change="handlerSearchDetail(1)"
                    class="radio"
                  >
                    <el-radio
                      v-for="(item, index) in typeList"
                      :key="index"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </div>
                <lineChart
                  v-if="activeName === '0'"
                  :lineData="lineData"
                  :mapData="mapData"
                  :precision="precision"
                />
                <barChart
                  v-else
                  :lineData="dataArr"
                  :xData="xData"
                  :mapData="mapData"
                  :precision="precision"
                  :yName="yName"
                />
              </el-col>
            </el-row>
            <lb-table
              ref="table"
              :column="tableData.column"
              :data="tableData.data"
              height="390"
              pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 30, 40, 100]"
              :pager-count="5"
              :current-page.sync="currentPage"
              :total="total"
              :page-size="pageSize"
              @size-change="handleSizeChange"
              @p-current-change="handleCurrentChange"
            >
              <!-- :summary-method="getSummaries" -->
              <!-- show-summary -->
            </lb-table>
          </el-col>
        </el-row>
      </div>
    </lb-layout>
    <detail
      :visible.sync="show"
      :id="id"
      :rowsData="rowsData"
      @close="close"
    ></detail>
  </div>
</template>

<script>
import {
  postemeterList,
  postWaterList,
  postelectricityChart,
  postwaterChart,
} from "@/api/iot/stream";
import CascaderSelect from "@/components/Select/CascaderSelect";
import detail from "@/views/statistics/energy/components/streamC/streamDetail.vue";
import RemoteSelect from "@/components/Select/RemoteSelect";
import lineChart from "@/views/statistics/energy/components/streamC/streamLinechart.vue";
import barChart from "@/views/statistics/energy/components/streamC/streamBarchart.vue";
import DictionariesSelect from "@/components/DictionariesSelect/index.vue";
import {
  dealElectricity,
  deepClone,
  secondChangedate,
  formatDate,
} from "@/utils/index";
import auth from "@/plugins/auth";
export default {
  dicts: [
    "device_model", // 电表型号
    "wmeter_device_model", // 水表型号
    "valve_status", // 闸门开关状态
    "voltage_status",
    "special_energy_consumption_type",
  ],
  components: {
    CascaderSelect,
    detail,
    RemoteSelect,
    lineChart,
    barChart,
    DictionariesSelect,
  },
  name: "stream",
  data() {
    return {
      tabloading: false,
      radio: 3,
      typeList: [
        {
          label: "能耗",
          value: 0,
        },
        {
          label: "电压",
          value: 1,
        },
        {
          label: "电流",
          value: 2,
        },
        {
          label: "功率",
          value: 3,
        },
      ],
      // tab
      activeName: "0",
      tabArr: [
        {
          label: "计量电表",
          value: "0",
          hasPermi: ["device:data:list"],
          show: false,
        },
        {
          label: "计量水表",
          value: "1",
          hasPermi: ["wmeter:data:list"],
          show: false,
        },
      ],
      dictArr: [],
      show: false,
      id: "",
      areaId: [],
      buildingList: [],
      sysDeptIdChose: null,
      sysDeptId: [],
      netwoekChose: null,
      rowsData: {},
      extraParams: {},
      parktreeProps: {
        value: "id",
        children: "childList",
        label: "name",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      areaProps: {
        value: "areaId",
        children: "children",
        label: "name",
        checkStrictly: true,
        expandTrigger: "hover",
      },
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            startAndend: {
              typeName: "el-date-picker",
              type: "datetimerange",
              size: "small",
              width: "300px",
              "start-placeholder": "",
              "end-placeholder": "",
              "value-format": "timestamp",
            },
            sysDeptId: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      value={that.sysDeptId}
                      values={that.sysDeptId}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"用能单位"}
                      onInput={(value) =>
                        this.handlerLiandong(value, "sysDeptId")
                      }
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            monitoringNetworkId: {
              typeName: "el-select",
              render: () => {
                let that = this;
                return (
                  <div>
                    <RemoteSelect
                      v-model={that.netwoekChose}
                      varient="networks"
                      extraParams={that.extraParams}
                      placeholder={"能耗终端"}
                      size={"small"}
                      onInput={that.choseNetwork}
                    ></RemoteSelect>
                  </div>
                );
              },
            },
            areaId: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      value={that.areaId}
                      values={that.areaId}
                      varient={"areaTree"}
                      propOptions={that.areaProps}
                      size={"small"}
                      placeholder={"省市区"}
                      onInput={(value) => this.handlerLiandong(value, "areaId")}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            buildingId: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      value={that.buildingList}
                      values={that.buildingList}
                      varient={"parkTree"}
                      propOptions={that.parktreeProps}
                      size={"small"}
                      placeholder={"建筑设施"}
                      onInput={(value) =>
                        this.handlerLiandong(value, "buildingId")
                      }
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            specialEnergyConsumptionType: {
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.special_energy_consumption_type.some(
                  (item) => {
                    arr.push(item);
                  }
                );
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue()
                    .specialEnergyConsumptionType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "特殊用能",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "specialEnergyConsumptionType",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            deviceModel: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dictArr.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().deviceModel;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "设备型号",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("deviceModel", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            deviceCode: {
              typeName: "el-input",
              placeholder: "设备编号",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              plain: true,
              click: this.handleReset,
            },
          ],
        },
      },
      tableData: {
        column: [],
        data: [],
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // linechart
      xData: [],
      lineData: {},
      dataArr: [],
      mapData: [],
      precision: 1,
      yName: "度",
      sumName: "",
      sumValue: "",
      eSum: 0, // 电耗
      wSum: 0, // 水耗
    };
  },
  created() {
    // this.judgePermi();
  },
  mounted() {
    this.routeSpecial();
  },
  methods: {
    judgePermi() {
      console.log(
        auth.hasPermi("device:data:list"),
        auth.hasPermi("wmeter:data:list")
      );
      if (auth.hasPermi("device:data:list")) {
        this.activeName = "0";
        this.tabArr[0].show = true;
      } else {
        this.tabArr[0].show = false;
        if (auth.hasPermi("wmeter:data:list")) {
          this.activeName = "1";
        } else {
          this.activeName = "";
        }
      }
      if (auth.hasPermi("wmeter:data:list")) {
        this.tabArr[1].show = true;
      } else {
        this.tabArr[1].show = false;
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (this.activeName == "0") {
          if (index === 0) {
            sums[index] = "电耗";
            return;
          } else if (index === 7) {
            sums[index] = this.eSum + " 度";
            return;
          } else {
            sums[index] = "";
            return;
          }
          // if (
          //   index === 5 ||
          //   index === 6 ||
          //   index === 8 ||
          //   index === 9 ||
          //   index === 10
          // ) {
          //   const values = data.map((item) =>
          //     Number(dealElectricity(item[column.property]))
          //   );
          //   if (!values.every((value) => isNaN(value))) {
          //     sums[index] = values.reduce((prev, curr) => {
          //       const value = Number(curr);
          //       if (!isNaN(value)) {
          //         return prev + curr;
          //       } else {
          //         return prev;
          //       }
          //     }, 0);
          //     if (index != 10) {
          //       sums[index] = sums[index].toFixed(2);
          //     } else {
          //       sums[index] = sums[index].toFixed(3);
          //     }
          //   }
          // } else {
          //   sums[index] = "";
          //   return;
          // }
        } else if (this.activeName == "1") {
          if (index === 0) {
            sums[index] = "水耗";
            return;
          }
          if (index === 6) {
            // const values = data.map((item) => Number(item[column.property]));
            // if (!values.every((value) => isNaN(value))) {
            //   sums[index] = values.reduce((prev, curr) => {
            //     const value = Number(curr);
            //     if (!isNaN(value)) {
            //       return prev + curr;
            //     } else {
            //       return prev;
            //     }
            //   }, 0);
            //   sums[index] += " 升";
            // }
            sums[index] = this.wSum + " 吨";
          } else {
            sums[index] = "";
            return;
          }
        }
      });
      return sums;
    },
    routeSpecial() {
      if (this.$route.query.tab != undefined) {
        this.activeName = this.$route.query.tab;
      }
      if (
        this.$route.query.deviceCode != undefined &&
        this.$route.query.deviceCode != ""
      ) {
        this.$refs?.form?.setFieldValue(
          "deviceCode",
          this.$route.query.deviceCode
        );
        this.handleChangetab(1);
      } else {
        this.handleChangetab();
      }
    },
    handleChangetab(flag) {
      this.tabloading = true;
      if (this.activeName == "0") {
        // 计量电表
        this.dictArr = this.dict.type.device_model;
        this.tableData.column = [
          {
            prop: "name",
            label: "能耗终端",
            minWidth: 120,
            showOverflowTooltip: true,
          },
          {
            prop: "deviceName",
            label: "设备名称",
            minWidth: 120,
            showOverflowTooltip: true,
          },
          {
            prop: "deviceCode",
            label: "设备编码",
            width: "150",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceModel",
            width: "120",
            label: "设备型号",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.device_model}
                    value={scope.row.deviceModel}
                  />
                </div>
              );
            },
          },
          {
            prop: "eventTime",
            width: "180",
            label: "抄表时间",
            sortable: true,
            showOverflowTooltip: true,
            render: (h, params) => {
              let date = secondChangedate(params.row.eventTimeStamp * 1000);
              return h("div", {}, date);
            },
          },

          {
            prop: "endElectricity",
            width: "180",
            label: "累计电量（kwh）",
            sortable: true,
            render: (h, params) => {
              let num = dealElectricity(params.row.endElectricity);
              return h("div", {}, num);
            },
          },
          {
            prop: "consumedElectricity",
            width: "180",
            label: "电量增值（kwh）",
            sortable: true,
            render: (h, params) => {
              let num = dealElectricity(params.row.consumedElectricity);
              return h("div", {}, num);
            },
          },
          {
            prop: "standardCoal",
            width: "180",
            label: "标准煤（kgce）",
            sortable: true,
            render: (h, params) => {
              let num = dealElectricity(params.row.standardCoal, 100, 4);
              return h("div", {}, num);
            },
          },
          {
            prop: "voltage",
            width: "150",
            label: "电压（V）",
            sortable: true,
            render: (h, params) => {
              let num = dealElectricity(params.row.voltage);
              return h("div", {}, num);
            },
          },
          {
            prop: "electricCurrent",
            width: "150",
            label: "电流（A）",
            sortable: true,
            render: (h, params) => {
              let num = dealElectricity(params.row.electricCurrent, 1000, 3);
              return h("div", {}, num);
            },
          },
          {
            prop: "activePower",
            width: "180",
            label: "有功功率（KW）",
            sortable: true,
            render: (h, params) => {
              let num = dealElectricity(params.row.activePower, 1000, 3);
              return h("div", {}, num);
            },
          },
          {
            label: "操作",
            width: "140",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              return (
                <div>
                  {
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-view"
                      onClick={() => {
                        this.id = scope.row.infoId;
                        this.rowsData = deepClone(scope.row);
                        this.show = true;
                      }}
                    >
                      详情
                    </el-button>
                  }
                </div>
              );
            },
          },
        ];
        this.apsForm.formConfig.properties.startAndend.type = "datetimerange"; // 时间日期选择器
        this.apsForm.formConfig.properties.startAndend["start-placeholder"] =
          "开始日期时间";
        this.apsForm.formConfig.properties.startAndend["end-placeholder"] =
          "结束日期时间";
        this.sumName = "电耗：";
        this.sumValue = this.eSum + " 度";
      } else if (this.activeName == "1") {
        // 计量水表
        this.dictArr = this.dict.type.wmeter_device_model;
        this.tableData.column = [
          {
            prop: "name",
            label: "能耗终端",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceName",
            label: "设备名称",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceCode",
            label: "设备编码",
            width: "150",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceModel",
            width: "120",
            label: "设备型号",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.wmeter_device_model}
                    value={scope.row.deviceModel}
                  />
                </div>
              );
            },
          },
          {
            prop: "receiveTime",
            width: "180",
            label: "抄表时间",
            align: "center",
            sortable: true,
            showOverflowTooltip: true,
            render: (h, params) => {
              let date = formatDate(params.row.receiveTime);
              return h("div", {}, date);
            },
          },
          {
            prop: "caliber",
            width: "180",
            label: "设备口径 （mm）",
            align: "center",
            sortable: true,
          },
          {
            prop: "deviceTotalData",
            width: "200",
            align: "center",
            label: "设备累计流量（升）",
            showOverflowTooltip: true,
            sortable: true,
          },
          {
            prop: "valveStatus",
            // width: "100",
            label: "开关状态",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.valve_status}
                    value={scope.row.valveStatus}
                  />
                </div>
              );
            },
          },
          {
            prop: "cardNum",
            width: "140",
            label: "物联网卡",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "signalIntensity",
            width: "120",
            label: "信号强度",
            align: "center",
            sortable: true,
          },
          {
            prop: "hardVersion",
            // width: "200",
            label: "固件版本",
            align: "center",
          },
          {
            prop: "uploadInterval",
            label: "数据上传间隔（min）",
            width: "200",
            align: "center",
            sortable: true,
          },
          {
            prop: "voltageStatus",
            width: "100",
            label: "电压状态",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.voltage_status}
                    value={scope.row.voltageStatus}
                  />
                </div>
              );
            },
          },
        ];
        this.apsForm.formConfig.properties.startAndend.type = "daterange"; // 日期选择器
        this.apsForm.formConfig.properties.startAndend["start-placeholder"] =
          "开始日期";
        this.apsForm.formConfig.properties.startAndend["end-placeholder"] =
          "结束日期";
        this.sumName = "水耗：";
        this.sumValue = this.wSum + " 吨";
      }
      if (flag == 1) {
        this.handlerSearchDetail();
      } else {
        this.handleReset();
      }
      this.$nextTick(() => {
        this.$refs.table.doLayout();
      });
      setTimeout(() => {
        this.tabloading = false;
      }, 500);
    },
    close(status) {
      this.show = false;
      // console.log(status);
      if (status) this.handlerSearchDetail();
    },
    // 图表数据请求
    async initChartdata(params) {
      // console.log(params, "图形参数");
      if (this.activeName == "0") {
        postelectricityChart(params)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            // console.log(res, "e");
            // let arr = res?.data?.realTimeEnergyConsumptionList ?? [];
            // let brr = res?.data?.realTimeSectionListVoList ?? [];
            this.eSum = res?.data?.cumulativePowerConsumption ?? 0;
            this.eSum = dealElectricity(this.eSum, 100, 3);
            // this.dealelectricity(arr, brr);
            this.yName = res?.data?.unit;
            this.sumValue = this.eSum + " " + this.yName;
            let arr = res?.data;
            let brr = res?.data?.listSectionA ?? [];
            this.electricityTarget(arr, brr);
          })
          .catch((err) => {
            // this.$message.error("系统错误,请联系管理员!200023");
          });
      } else if (this.activeName == "1") {
        postwaterChart(params)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            // console.log(res, "w");
            let arr = res?.data?.wmeterRealTimeLoadVoList ?? [];
            let brr = res?.data?.realTimeSectionVoList ?? [];
            this.wSum = res?.data?.cumulativeWaterConsumption ?? 0;
            this.wSum = dealElectricity(this.wSum, 1000, 3);
            this.dealwater(arr, brr);
            this.sumValue = this.wSum + " 吨";
          })
          .catch((err) => {
            // this.$message.error("系统错误,请联系管理员!200024");
          });
      }
    },
    electricityTarget(data, brr) {
      // console.log(data, "3123");
      this.mapData = [];
      this.precision = 1;
      let num = Number(data.graphNum);
      let multiple = data.multiple;
      data.listASeries = [];
      data.listBSeries = [];
      data.listCSeries = [];
      if (num == 1) {
        if (data.listA && data.listA.length === 0) {
          data.listASeries = [];
        } else {
          data.listA.map((item) => {
            data.listASeries.push([
              item.dateStr,
              Number(dealElectricity(item?.value ?? 0, multiple, 3)),
            ]);
          });
        }
      } else if (num == 2) {
        if (data.listA && data.listA.length === 0) {
          data.listASeries = [];
        } else {
          data.listA.map((item) => {
            data.listASeries.push([
              item.dateStr,
              Number(dealElectricity(item?.value ?? 0, multiple, 3)),
            ]);
          });
        }
        if (data.listB && data.listB.length === 0) {
          data.listBSeries = [];
        } else {
          data.listB.map((item) => {
            data.listBSeries.push([
              item.dateStr,
              Number(dealElectricity(item?.value ?? 0, multiple, 3)),
            ]);
          });
        }
      } else if (num == 3) {
        if (data.listA && data.listA.length === 0) {
          data.listASeries = [];
        } else {
          data.listA.map((item) => {
            data.listASeries.push([
              item.dateStr,
              Number(dealElectricity(item?.value ?? 0, multiple, 3)),
            ]);
          });
        }
        if (data.listB && data.listB.length === 0) {
          data.listBSeries = [];
        } else {
          data.listB.map((item) => {
            data.listBSeries.push([
              item.dateStr,
              Number(dealElectricity(item?.value ?? 0, multiple, 3)),
            ]);
          });
        }
        if (data.listC && data.listC.length === 0) {
          data.listCSeries = [];
        } else {
          data.listC.map((item) => {
            data.listCSeries.push([
              item.dateStr,
              Number(dealElectricity(item?.value ?? 0, multiple, 3)),
            ]);
          });
        }
      }

      let colorArr = [
        "#93CE07",
        "#FBDB0F",
        "#FC7D02",
        "#FD0100",
        "#AA069F",
        "#AC3B2A",
      ];
      if (brr.length === 0) {
        this.mapData = [
          {
            gt: 0,
            lte: 10000000,
            color: "green",
          },
        ];
      } else {
        brr.map((item, index) => {
          let obj = {
            gt: Number(dealElectricity(brr[index]?.gt ?? 0, multiple, 3)),
            lte: Number(dealElectricity(brr[index]?.lt ?? 1, multiple, 3)),
            color: colorArr[index],
          };
          this.mapData.push(obj);
        });
      }
      this.lineData = data;
      // console.log(this.lineData, "lineData");
    },
    dealwater(arr, brr) {
      this.dataArr = [];
      this.xData = [];
      this.mapData = [];
      this.precision = 1;
      this.yName = "T";
      if (arr.length === 0) {
        this.xData = [];
        this.dataArr = [];
      } else {
        arr.map((item) => {
          this.xData.push(item?.dateStr ?? "时刻");
          this.dataArr.push(
            Number(dealElectricity(item?.waterConsumption ?? 0, 1000, 3))
          );
        });
      }
      let colorArr = [
        "#93CE07",
        "#FBDB0F",
        "#FC7D02",
        "#FD0100",
        "#AA069F",
        "#AC3B2A",
      ];
      if (brr.length === 0) {
        this.mapData = [
          {
            gt: 0,
            lte: 1,
            color: "#000000",
          },
        ];
      } else {
        brr.map((item, index) => {
          let obj = {
            gt: Number(dealElectricity(brr[index]?.gt ?? 0, 1000, 3)),
            lte: Number(dealElectricity(brr[index]?.lt ?? 1, 1000, 3)),
            color: colorArr[index],
          };
          this.mapData.push(obj);
        });
      }
    },
    async initData(data) {
      // const datas = data && Object.keys(data).length > 0 ? data : {};
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      // if (!query.sysDeptId && !query.monitoringNetworkId) {
      //   that.$message.error("需选择用能单位或者能耗终端才可搜索");
      // } else {
      that.$store.commit("app/updateApiCount", "add");
      let requestWay, errCode;
      if (this.activeName == "0") {
        requestWay = postemeterList;
        errCode = "20002";
      } else if (this.activeName == "1") {
        requestWay = postWaterList;
        errCode = "200022";
      }
      await requestWay(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!" + errCode);
        });
      // }
    },
    /* 搜索 */
    handlerSearchDetail() {
      const { startAndend, ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
        monitoringNetworkId: this.netwoekChose,
        queryFlag: this.radio,
        areaId: this.areaId[this.areaId.length - 1],
        buildingId: this.buildingList[this.buildingList.length - 1],
        sysDeptId: this.sysDeptId[this.sysDeptId.length - 1],
      };
      if (startAndend) {
        data.startTimeStamp = startAndend[0] / 1000;
        data.endTimeStamp = startAndend[1] / 1000;
      }
      this.initData(data);
      this.initChartdata(data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    //重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.sysDeptIdChose = null;
      this.sysDeptId = [];
      this.buildingList = [];
      this.areaId = [];
      this.netwoekChose = null;
      this.extraParams = {};
      // this.$nextTick(() => {
      this.handlerSearchDetail();
      // });
    },
    // 联动
    handlerLiandong(value, key) {
      this.netwoekChose = null;
      // this.sysDeptIdChose = value[value.length - 1];
      // 请求能耗终端
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      if (key === "sysDeptId")
        this.extraParams = {
          [key]: result,
        };
    },
    /* 选择能耗终端 */
    choseNetwork(value) {
      this.netwoekChose = value;
    },
  },
};
</script>

<style lang="scss" scoped>
.text-tabs {
  margin: -20px 0 5px -40px;
}
.iot-energy {
  position: relative;
  .sum-area {
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 99;
    cursor: default;
  }
}
.chart-area {
  z-index: 2;
  margin-top: -10px;
  .total {
    position: absolute;
    right: 0;
    bottom: 200px;
    span {
      &:nth-child(2) {
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #3385ff;
        line-height: 28px;
      }
    }
  }
}
</style>
